import React,{Component} from 'react';
import {Platform, ScrollView, StyleSheet, Text, View,Image,StatusBar,TouchableOpacity} from 'react-native'
import {Button,Modal,Toast,WhiteSpace,Checkbox,Radio,Tabs,Switch,ListView,Provider,InputItem,List} from '@ant-design/react-native'
import {getTypesAndProduct} from '../api/api'
import BasePage from '../base/BasePage'
import Icon from 'react-native-vector-icons/FontAwesome5';


//主页面
export default class HomePage extends BasePage {
	static navigationOptions = {
		tabBarLabel: 'Home',
		tabBarIcon: ({focused, tintColor}) => {
			if (focused) {
				return (
					<Icon name={'microsoft'} size={commonStyle.tabBarSize} color={tintColor}/>
				);
			}
			return (
				<Icon name={'robot'}  size={commonStyle.tabBarSize} />
			);
		},
	};
	constructor(props) {
        super(props);
		//写变量的地方
        this.state = {
        	...this.BaseState,
            selectedTab:'redTab',
			loading:false,
            firstInit:true,
			checked: false,
			hidden:true,
			layout:'list',
            pageSize:15,
            currentTab:0,
            tabs2 : [],
			respData:[],
			visible: false,
		};
		this.onSwitchChange = value => {
			this.setState({
				checked: value,
			});
		};
		this.onClose = () => {
			this.setState({
			  visible: false,
			});
		  };
		
	}
	renderItem = (product) => {
		return (
			<View  style={styles.tablist}>
				<View style={styles.list_top}>
					<Text style={[styles.top_left,styles.green]}>{product.name}</Text>
					<Text style={styles.top_right}>预估：<Text style={styles.green}>{product.planNum}{product.unit}</Text></Text>
				</View>
				<View style={styles.list_center}>
					<Text style={styles.center_a1}>数量：<Text style={styles.red}>{product.actualNum?product.actualNum:0}{product.unit}</Text></Text>
					<Text style={styles.center_a1}>采购价：<Text style={styles.red}>￥{product.actualPrice?product.actualPrice:0}</Text></Text>
					<Text style={styles.center_a1}>总价：<Text style={styles.red}>￥{product.actualNum * product.actualPrice}</Text></Text>
				</View> 
				<View style={styles.list_center}>
					<Text style={styles.center_a1}>销售价：<Text style={commonStyle.orange}>￥{product.salePrice?product.salePrice:0}</Text></Text>
					<Text style={styles.center_a1}>加价：<Text style={commonStyle.orange}>+{product.increaseAmount?product.increaseAmount:0}</Text></Text>
					<Text style={styles.center_a1}>差价率：<Text style={commonStyle.orange}>{product.increaseRatio?product.increaseRatio:0}%</Text></Text>
				</View>
				<View style={styles.list_bottom}>
					<View style={styles.bottom_left}>
						<Checkbox checked={this.state.checked} style={{width:25,height:20,color:'#0abe73'}} onChange={this.onSwitchChange}></Checkbox>
						<Text style={styles.gray}>装车</Text>
					</View>
					<Button style={styles.btn_green} onPress={this.showModal} ><Text style={styles.btn_white}>点击输入</Text></Button>
				</View>
			</View>	
		);
	};
	sleep = time => new Promise(resolve => setTimeout(() => resolve(), time))

	showModal = () => {
		console.log('[start touch]')
		this.setState({ visible: true })
		console.log('[ touch]')
	}

	onFetch = async (page = 1, startFetch, abortFetch) => {
		try {
			let pageLimit = 100;
            await this.sleep(10); 

            console.log(111,this.state.currentTab)
            if(this.state.respData.length == 0) {
                await this.loadData();
            }
			let productList = this.state.respData[this.state.currentTab].productList;
            if(this.state.firstInit) {
                this.setState({currentTab:1,firstInit:false})
            } 
			startFetch(productList, pageLimit);
		  } catch (err) {
			abortFetch(); //manually stop the refresh or pagination if it encounters network error
		  }
	}
 
    _Separator = () => {
        return <View style={{height:0.5,backgroundColor:'#ddd',}}/>
    }
	
	//写页面的地方
	renderPage() {
		const navigation = this.props.navigation;
		const footerButtons = [
		{ text: '取消', onPress: () => console.log('cancel') },
		{ text: '提交', onPress: () => console.log('ok') },
		];
		//在这写页面！！！
    	return (
			<Provider>
				<View style={styles.container}>
					<Tabs tabs={this.state.tabs2} initialPage={0}
						onChange={(tab,index) => {console.log('index',index);this.setState({currentTab:index+1})}}
						tabBarTextStyle={styles.tabtit} tabBarUnderlineStyle={styles.tabtitline}  
						tabBarInactiveTextColor="#333" tabBarActiveTextColor="#0abe73" tabBarPosition="top">
						<ListView
							onFetch={this.onFetch}
							keyExtractor={(item, index) => `${index}`}
							renderItem={this.renderItem}
							refreshable={false}
							separator={this._Separator}
							style={styles.list_view}
						/>
						
					</Tabs>
					<Button type="primary" style={styles.footbtn} onPress={()=>{navigation.navigate('BlueTest')}}>测试蓝牙打印小票</Button>
					<Modal
						transparent
						onClose={this.onClose}
						maskClosable
						visible={this.state.visible}
						footer={footerButtons}
					>
						 <List style={styles.modal_list}>
							<InputItem
								clear
								value={this.state.value}
								onChange={value => {
								this.setState({
									value,
								});
								}}
								extra="元"
								placeholder="请输入"
							>
								数量
							</InputItem>
							<InputItem
								clear
								value=""
								onChange={value => {
								this.setState({
									value,
								});
								}}
								extra="元"
								placeholder="请输入"
								
							>
								采购价
							</InputItem>
							
							<InputItem
								
								clear
								extra="元"
								placeholder="请输入"
								
							>
								销售价
							</InputItem>
							
						</List>
						
					</Modal>
				</View>
			</Provider>
    	)
    }

    componentDidMount() {
        this.loadData()
    }

    async loadData() {
        if(this.state.loading) return
        this.setState({loading:true})
        let resp = await getTypesAndProduct();
        let typeList = [];
        resp.typeList.map(m => {
            typeList.push({title : m.name})
        })
        this.setState({tabs2:typeList,respData:resp.typeList})
        this.setState({loading:false})
    }


}

//写样式的地方，只在这写样式，该怎么写就怎么写
const styles = StyleSheet.create({
	container:{
		flex: 1, 
		backgroundColor: 'white'
	},
	green:{
		color:'#0abe73',
	},
	red:{
		color:'#f30',
	},
	orange:{
		color:'#f80',
	},
	gray:{
		color:'#999',
	},
	white:{
		color:'#fff',
	},
	tabtit: {
		fontSize:16,
	},
	tabtitline:{
		backgroundColor: '#0abe73'
	},
	separator:{

    },
	tablist:{
		paddingTop:10,
		paddingLeft:10,
		paddingRight:10,
		paddingBottom:20,
	},
	list_top:{
		flexDirection:'row',
		justifyContent: 'space-between',
		fontSize:14,
		marginBottom:10,
	},
	top_left:{
		fontSize:16,
	},
	top_right:{
		color:'#999',
	},
	list_center:{
		flexDirection:'row',
		marginBottom:10,
	},
	center_a1:{
		marginRight:10,
		color:'#999',
	},
	list_bottom:{
		flexDirection:'row',
		justifyContent: 'space-between',
	},
	bottom_left:{
		flexDirection:'row',
		alignItems:'center',
	},
	btn_green:{
		height:35,
		backgroundColor:'#0abe73',
		borderWidth:0,
	},
	btn_white:{
		color:'#fff',
		fontSize:14,
	},
	footbtn:{
		borderRadius:0,
	},
	modal_list:{
		borderWidth:0,
	},
})